<?php
namespace app\home\behavior;
/**
 * 前台需要验证会员是否登录的url
 * user表 会员类型$userType 0普通会员，1商家
 * home_menu表 菜单类型$menuType 1会员菜单，2商家菜单
 */
class ListenProtectedUrl{
  public function run($params) {
    $request = request();
    $urls = ZHTConf('protectedUrl');
    $visit = strtolower($request->module() . "/" . $request->controller() . "/" . $request->action());

    //受保护资源进来检测身份
    if (isset($urls[$visit])) {
      $menuType = (int)$urls[$visit];
      $userType = -1;
      $shopId = (int)session('ZHT_USER.shopId');
      if ((int)session('ZHT_USER.userId') > 0) $userType = 0;
      if ($shopId > 0) $userType = 1;

      //未登录不允许访问受保护的资源
      if ($userType == -1) {
        if ($request->isAjax()) {
          echo json_encode(['status' => -999, 'msg' => '对不起，您还没有登录，请先登录']);
        } else {
          header("Location:" . url('home/user/login'));
        }
        exit();
      } else if ($userType == 1) {
        $puser = session('ZHT_USER');
        if (isset($puser['shopId'])) {
          $shop = model('shop')->getFieldsById($shopId, 'shopStatus');
          if (empty($shop) || $shop['shopStatus'] == -1) {
            model('User')->logout();
            if ($request->isAjax()) {
              echo json_encode(['status' => -999, 'msg' => '对不起，您的店铺已停用']);
            } else {
              header("Location:" . url('shop/index/login'));
            }
            exit();
          }
        }
      } else {
        //已登录但不是商家 则不允许访问受保护的商家资源
        if ($menuType == 2) {
          if ($request->isAjax()) {
            echo json_encode(['status' => -999, 'msg' => '对不起，您不是商家，请先申请为商家再访问']);
          } else {
            header("Location:" . url('shop/index/login'));
          }
          exit();
        }
      }
      //商家角色权限
      if (((int)session('ZHT_USER.roleId') > 0) && $userType == 1 && $menuType == 2) {
        $shopMenuUrls = model('HomeMenu')->getShopMenusUrl();
        if (!in_array($visit, $shopMenuUrls)) {
          header("Location:" . url('home/error/index'));
          exit();
        }
      }
    }
  }
}